package com.pyue.eam.admin.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pyue.eam.admin.api.entity.SysDict;
import com.pyue.eam.admin.api.entity.SysDictItem;
import com.pyue.eam.admin.api.entity.regi.ClientLibEntity;
import com.pyue.eam.admin.api.entity.regi.CqCarModelEntity;
import com.pyue.eam.admin.api.entity.regi.CqFailureModesEntity;
import com.pyue.eam.admin.api.entity.regi.PartLibEntity;
import com.pyue.eam.admin.mapper.SysDictItemMapper;
import com.pyue.eam.admin.service.SysDictItemService;
import com.pyue.eam.admin.service.SysDictService;
import com.pyue.eam.common.core.constant.CacheConstants;
import com.pyue.eam.common.core.constant.enums.DictTypeEnum;
import com.pyue.eam.common.core.exception.ErrorCodes;
import com.pyue.eam.common.core.util.MsgUtils;
import com.pyue.eam.common.core.util.R;
import com.pyue.eam.regi.service.ClientLibService;
import com.pyue.eam.regi.service.CqCarModelService;
import com.pyue.eam.regi.service.CqFailureModesService;
import com.pyue.eam.regi.service.PartLibService;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典项
 *
 * @author eam
 * @date 2019/03/19
 */
@Service
@AllArgsConstructor
public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem> implements SysDictItemService {
    private final SysDictService dictService;
    private final CqCarModelService cqCarModelService;
    private final ClientLibService clientLibService;
    private final PartLibService partLibService;
    private final CqFailureModesService cqFailureModesService;

    /**
     * 删除字典项
     *
     * @param id 字典项ID
     * @return
     */
    @Override
    @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
    public R removeDictItem(Long id) {
        // 根据ID查询字典ID
        SysDictItem dictItem = this.getById(id);
        SysDict dict = dictService.getById(dictItem.getDictId());
        // 系统内置
        if (DictTypeEnum.SYSTEM.getType().equals(dict.getSystemFlag())) {
            return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_DICT_DELETE_SYSTEM));
        }
        return R.ok(this.removeById(id));
    }

    /**
     * 更新字典项
     *
     * @param item 字典项
     * @return
     */
    @Override
    @CacheEvict(value = CacheConstants.DICT_DETAILS, key = "#item.dictType")
    public R updateDictItem(SysDictItem item) {
        // 查询字典
        SysDict dict = dictService.getById(item.getDictId());
        // 系统内置
        if (DictTypeEnum.SYSTEM.getType().equals(dict.getSystemFlag())) {
            return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_DICT_UPDATE_SYSTEM));
        }
        return R.ok(this.updateById(item));
    }

    @Override
    public List<SysDictItem> dictByType(String type) {
        // 扩展字典
        switch (type) {
            case "client":
                List<ClientLibEntity> libEntityList = clientLibService.list(Wrappers.lambdaQuery(ClientLibEntity.class).select(ClientLibEntity::getClientId,
                        ClientLibEntity::getClientCode, ClientLibEntity::getShortName));

                return libEntityList.stream().filter(e -> StrUtil.isNotBlank(e.getShortName())).sorted(Comparator.comparing(ClientLibEntity::getShortName)).map(e -> {
                    SysDictItem sysDictItem = new SysDictItem();
                    sysDictItem.setItemValue(Convert.toStr(e.getClientId()));
                    sysDictItem.setLabel(Convert.toStr(e.getClientCode(), e.getShortName()));
                    return sysDictItem;
                }).collect(Collectors.toList());
            case "part":
                List<PartLibEntity> partLibEntityList = partLibService.list(Wrappers.lambdaQuery(PartLibEntity.class).select(PartLibEntity::getId,
                        PartLibEntity::getPartCode, PartLibEntity::getPartName,PartLibEntity::getCarType));

                return partLibEntityList.stream().filter(e -> StrUtil.isNotBlank(e.getPartCode())).sorted(Comparator.comparing(PartLibEntity::getPartCode)).map(e -> {
                    SysDictItem sysDictItem = new SysDictItem();
                    sysDictItem.setItemValue(Convert.toStr(e.getId()));
                    String part = Convert.toStr(e.getPartCode(), e.getPartName());
                    if (StrUtil.isNotBlank(e.getCarTypeTrans())) {
                        part = StrUtil.concat(Boolean.TRUE, part, "/", e.getCarTypeTrans());
                    }
                    sysDictItem.setLabel(part);
                    // sysDictItem.setLabel(Convert.toStr(e.getPartCode(), e.getPartName()));
                    return sysDictItem;
                }).collect(Collectors.toList());
            case "car":
                List<CqCarModelEntity> cqCarModelEntitieList =
                        cqCarModelService.list(Wrappers.lambdaQuery(CqCarModelEntity.class).select(CqCarModelEntity::getId, CqCarModelEntity::getModelCode,
                                CqCarModelEntity::getModelName));

                return cqCarModelEntitieList.stream().filter(e -> StrUtil.isNotBlank(e.getModelCode())).sorted(Comparator.comparing(CqCarModelEntity::getModelCode)).map(e -> {
                    SysDictItem sysDictItem = new SysDictItem();
                    sysDictItem.setItemValue(Convert.toStr(e.getId()));
                    sysDictItem.setLabel(Convert.toStr(e.getModelCode(), e.getModelName()));
                    return sysDictItem;
                }).collect(Collectors.toList());

            case "failure_modes":
                List<CqFailureModesEntity> list =
                        cqFailureModesService.list(Wrappers.lambdaQuery(CqFailureModesEntity.class).select(CqFailureModesEntity::getId,
                                CqFailureModesEntity::getName, CqFailureModesEntity::getDescription));
                return list.stream().filter(e -> StrUtil.isNotBlank(e.getName())).sorted(Comparator.comparing(CqFailureModesEntity::getName)).map(e -> {
                    SysDictItem sysDictItem = new SysDictItem();
                    sysDictItem.setItemValue(Convert.toStr(e.getId()));
                    sysDictItem.setLabel(e.getName());
                    return sysDictItem;
                }).collect(Collectors.toList());
            default:
                return dictData(type);
        }
    }

    @Cacheable(value = CacheConstants.DICT_DETAILS, key = "#type", unless = "#result.isEmpty()")
    public List<SysDictItem> dictData(String type) {
        return list(Wrappers.<SysDictItem>query().lambda().eq(SysDictItem::getDictType, type));
    }


}
